<template>
  <div class="shelf-footer" v-show="isEditMode">
    <div
      class="shelf-footer-tab-wrapper"
      v-for="(item, index) in tabs"
      :key="index"
      @click="onTabClick(item)"
    >
      <div class="shelf-footer-tab" :class="{ 'is-selected': isSelected }">
        <div
          class="icon-private tab-icon"
          v-if="item.index === 1 && !isPrivate"
        ></div>
        <div
          class="icon-private-see tab-icon"
          v-if="item.index === 1 && isPrivate"
        ></div>
        <div
          class="icon-download tab-icon"
          v-if="item.index === 2 && !isDownload"
        ></div>
        <div
          class="icon-download-remove tab-icon"
          v-if="item.index === 2 && isDownload"
        ></div>
        <div class="icon-move tab-icon" v-if="item.index === 3"></div>
        <div class="icon-shelf tab-icon" v-if="item.index === 4"></div>
        <div class="tab-text">{{ label(item) }}</div>
      </div>
    </div>
  </div>
</template>

<script>
import { storeShelfMixin } from '../../utils/mixin'
import { getBookShelf, removeLocalStorage, saveBookShelf } from '../../utils/localStorage'
import { download } from '../../api/store'
import { removeLocalForage } from '../../utils/localForage'
export default {
  mixins: [storeShelfMixin],
  data() {
    return {
      popupMeun: null,
      toastMeun: null
    }
  },
  computed: {
    isSelected() {
      return this.shelfSelected && this.shelfSelected.length > 0
    },
    tabs() {
      return [
        {
          label: this.$t('shelf.private'),
          label2: this.$t('shelf.noPrivate'),
          index: 1
        },
        {
          label: this.$t('shelf.download'),
          label2: this.$t('shelf.delete'),
          index: 2
        },
        {
          label: this.$t('shelf.move'),
          index: 3
        },
        {
          label: this.$t('shelf.remove'),
          index: 4
        }
      ]
    },
    // 判断是否为私密状态 (关键)
    isPrivate() {
      if (!this.isSelected) {
        return false
      } else {
        // 需要每一本书都是private 状态
        return this.shelfSelected.every((item) => item.private)
      }
    },
    isDownload() {
      if (!this.isSelected) {
        return false
      } else {
        return this.shelfSelected.every((item) => item.cache)
      }
    }
  },
  methods: {
    // 结合 indexedDB 实现电子书下载
    async downlocadSelectedBook() {
      for (let i = 0; i < this.shelfSelected.length; i++) {
        await this.downloadBook(this.shelfSelected[i]).then((book) => {
          // 通过异步将 cache 状态设为 true
          this.shelfSelected[i].cache = true
        })
      }
    },
    downloadBook(book) {
      const text = ''
      this.toastMeun = this.toast({
        text
      })
      this.toastMeun.continueShow()
      // 通过promise
      return new Promise((resolve, reject) => {
        // 调用API
        // 具体功能 ： 传入book 先将电子书下载下来
        // 下载电子书需要 分类名称 和 电子书名 从 book里面获取 并且拼接 通过nginx 下载
        download(book, (res) => {
          console.log('下载完毕')
          /*
        这里实际上未销毁 里面的值还保留着
        当执行这段时 toast.updataText(text)
        create-api 机制是没有办法去更新这个值的
          */
          // toast.hide()
          this.toastMeun.remove() // 调用create-api 方法 将toast remove掉
          resolve(book)
        }, reject, progressEvent => {
          // 这里发现下载速度太快 切换为线上下载
          // VUE_APP_EPUB_URL=http://47.99.166.157/epub
          // loaded 当前读的多少 total 总共读多少 两个一比较就得到下载进度
          const progress = Math.floor(progressEvent.loaded / progressEvent.total * 100)
          const text = this.$t('shelf.progressDownload').replace('$1', `${book.fileName}.epub(${progress})`)
          this.toastMeun.updataText(text)
        })
      })
    },
    // label(item) {
    //   // 非选中状态
    //   if (this.isSelected) {
    //     return this.isPrivate ? (!item.label2 ? item.label : item.label2) : item.label
    //   } else {
    //     return item.label
    //   }
    // },
    label(item) {
      switch (item.index) {
        case 1:
          return this.isPrivate ? item.label2 : item.label
        case 2:
          return this.isDownload ? item.label2 : item.label
        default:
          return item.label
      }
    },
    onCompleted() {
      this.hidePopup()
      this.setIsEditMode(false)
      saveBookShelf(this.shelfList)
    },
    // 设置私密阅读
    setPrivate() {
      let isPrivate
      if (this.isPrivate) {
        // 如果选中的都是私密阅读  设为false
        isPrivate = false
      } else {
        // 如果不是 或者都不是 则设置为true
        isPrivate = true
      }
      // 数据源发生改变 ？ ？ ？
      this.shelfSelected.forEach((book) => {
        book.private = isPrivate
      })
      /**
       * 两个vuex中的数据毫不相干为什么可以相互影响
       *
       * */
      if (isPrivate) {
        console.log(isPrivate)
        this.simpleToast(this.$t('shelf.setPrivateSuccess'))
      } else {
        this.simpleToast(this.$t('shelf.closePrivateSuccess'))
      }
      this.onCompleted()
    },
    // 隐藏私密阅读
    hidePrivate() {
      this.hidePopup()
    },
    // 隐藏弹窗
    hidePopup() {
      this.popupMeun.hide()
    },
    // 私密阅读
    showPrivate() {
      this.popupMeun = this.popup({
        title: this.isPrivate
          ? this.$t('shelf.closePrivateTitle')
          : this.$t('shelf.setPrivateTitle'),
        btn: [
          {
            text: this.isPrivate
              ? this.$t('shelf.close')
              : this.$t('shelf.open'),
            click: () => {
              this.setPrivate()
            }
          },
          {
            text: this.$t('shelf.cancel'),
            click: () => {
              this.hidePopup()
            }
          }
        ]
      }).show()
    },
    // 删除缓存功能
    removeSelectedBook() {
      Promise.all(this.shelfSelected.map(book => this.removeBook(book)))
        .then((books) => {
          books.cache = false
        })
      saveBookShelf(this.shelfList)
      this.simpleToast(this.$t('shelf.removeDownloadSuccess'))
    },
    removeBook(book) {
      return new Promise((resolve, reject) => {
        removeLocalStorage(`${book.categoryText}/${book.fileName}-info`)
        removeLocalForage(`${book.fileName}`)
        resolve(book)
      })
    },
    // 设置缓存
    async setDownload() {
      let isDownload
      if (this.isDownload) {
        isDownload = false
      } else {
        isDownload = true
      }
      this.shelfSelected.forEach((item) => {
        item.cache = isDownload
      })
      if (isDownload) {
        await this.downlocadSelectedBook()
        // 这里因为 Toast 显示时间为1.5秒 当电子书未下载完 Toast 就关闭了
        // 说明这两句代码在同时执行
        // 也就是没有显示 所以通过 async await 解决
        // 解决异步后 这里还是没打印出来 是 create-api 机制问题
        this.simpleToast(this.$t('shelf.setDownloadSuccess'))
      } else {
        this.toastMeun.remove() // 解决 removeDownloadSuccess 不显示问题
        this.removeSelectedBook()
        saveBookShelf(this.shelfList)
      }
      this.onCompleted()
    },
    // 开启离线缓存
    showDownload() {
      if (this.shelfSelected) {
        this.popupMeun = this.popup({
          title: this.isDownload
            ? this.$t('shelf.removeDownloadTitle')
            : this.$t('shelf.setDownloadTitle'),
          btn: [
            {
              text: this.isDownload
                ? this.$t('shelf.delete')
                : this.$t('shelf.open'),
              click: () => {
                this.setDownload()
              }
            },
            {
              text: this.$t('shelf.cancel'),
              click: () => {
                this.hidePopup()
              }
            }
          ]
        }).show()
      }
    },
    // 移除书架功能
    removeSelected() {
      this.shelfSelected.forEach((item) => {
        this.setShelfList(this.shelfList.filter((list) => list !== item))
      })
      this.setShelfSelected([])
      getBookShelf()
      this.onCompleted()
    },
    // 移除书架弹框
    showRemove() {
      let title
      if (this.shelfSelected.length === 1) {
        title = this.$t('shelf.removeBookTitle').replace(
          '$1',
          `《${this.shelfSelected[0].title}》`
        )
      } else {
        title = this.$t('shelf.removeBookTitle').replace(
          '$1',
          this.shelfSelected.length
        )
      }
      this.popupMeun = this.popup({
        title: title,
        btn: [
          {
            text: this.$t('shelf.remove'),
            type: 'danger',
            click: () => {
              this.removeSelected()
            }
          },
          {
            text: this.$t('shelf.cancel'),
            click: () => {}
          }
        ]
      }).show()
    },
    onTabClick(item) {
      if (!this.isSelected) {
        return
      }
      switch (item.index) {
        case 1:
          // 私密阅读
          this.showPrivate()
          break
        case 2:
          // 离线下载
          this.showDownload()
          break
        case 3:
          this.dialog().show()
          break
        case 4:
          this.showRemove()
          break
        default:
          break
      }
    }
  }
}
</script>

<style lang='scss' scopde>
@import '../../assets/style/global.scss';
.shelf-footer {
  position: fixed;
  bottom: 0;
  left: 0;
  z-index: 120;
  display: flex;
  width: 100%;
  height: px2rem(48);
  background: white;
  box-shadow: 0 px2rem(-2) px2rem(4) 0 rgba(0, 0, 0, 0.1);
  .shelf-footer-tab-wrapper {
    flex: 1;
    width: 25%;
    height: 100%;
    padding-top: px2rem(5);
    .shelf-footer-tab {
      opacity: 0.5;
      @include columnCenter;
      &.is-selected {
        opacity: 1;
      }
      .tab-icon {
        font-size: px2rem(20);
        color: #666;
      }
      .tab-text {
        margin-top: px2rem(5);
        font-size: px2rem(12);
        color: #666;
      }
      .icon-shelf {
        color: $color-pink;
      }
    }
  }
}
</style>
